<template >
    <div>
      <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button style="float:right; margin-right: 30px" type="success" @click="exportExcel">导出</el-button>
  
          <el-button style="float:right; margin-right: 15px" @click="uploadExcel()">上传</el-button>
  
          <el-button style="float:right; margin-right: 30px" type="primary" @click="getcropAnalysList()">查询</el-button>
          <el-button style="float:right; margin-right: 15px" @click="handleResetSearch()">重置</el-button>
        </div>
        <!-- 文件上传窗口 -->
        <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
            <el-upload class="upload-demo" drag action="" :show-file-list="false" :before-upload="handleBeforeUpload"
              :on-change="handleFileChange">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">点击或拖拽文件(.xlsx)到此区域进行上传</div>
            </el-upload>
            <el-table :data="uploadedData" v-if="uploadedData.length">
                <el-table-column prop="年份" label="年份" />
                <el-table-column prop="城市" label="城市" />
                <el-table-column prop="区县" label="区县" />
                <el-table-column prop="作物种类" label="作物种类" />
                <el-table-column prop="AOT40" label="AOT40" />  
                <el-table-column prop="MDA8" label="MDA8" />
                <el-table-column prop="SUM06" label="SUM06" />
                <el-table-column prop="RYL" label="RYL" />
            </el-table>
            <template #footer>
              <el-button @click="uploadData">上传</el-button>
              <el-button @click="uploadDialogVisible = false">取 消</el-button>
            </template>
          </el-dialog>
        <div style="margin-top: 30px; ">
          <el-form style="display: inline-block;">
            <div style="display: inline-block;margin-left:20px">
              <el-form-item label="城市：">
                <el-input class="input-width" placeholder="城市" v-model="queryParams.param.city" clearable></el-input>
              </el-form-item>
            </div>
            <div style="display: inline-block;margin-left:20px">
              <el-form-item label="区县：">
                <el-input class="input-width" placeholder="区县" v-model="queryParams.param.county" clearable></el-input>
              </el-form-item>
            </div>
            <div style="display: inline-block;margin-left:20px">
              <el-form-item label="年份：">
                <el-input class="input-width" placeholder="年份" v-model="queryParams.param.year" clearable></el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
      <el-table ref="multipleTableRef" :data="cropAnalysList" style="width:100%" :broder="true" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="year" label="年份" />
        <el-table-column prop="city" label="城市" />
        <el-table-column prop="county" label="区县" />
        <el-table-column prop="crop" label="作物种类" />
        <el-table-column prop="aot40" label="AOT40" />  
        <el-table-column prop="mda8" label="MDA8" />
        <el-table-column prop="sum06" label="SUM06" />
        <el-table-column prop="ryl" label="RYL" />
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)" type="primary">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div>
        <el-pagination :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" :page-sizes="[15, 30, 45]"
          :small="false" :disabled="false" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="total" @size-change="handleSizeChange" @current-change="handleNumChange" />
      </div>
  
      <!-- 编辑框 -->
      <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="修改信息" width="800">
        <el-form ref="formRef" :model="updateForm" :rules="rules">
          <el-form-item prop="year" label="年份：">
            <el-input v-model="updateForm.year" />
          </el-form-item>
          <el-form-item prop="city" label="城市：">
            <el-input v-model="updateForm.city" />
          </el-form-item>
          <el-form-item prop="county" label="区县：">
            <el-input v-model="updateForm.county" />
          </el-form-item>
          <el-form-item prop="crop" label="作物种类：">
            <el-input v-model="updateForm.crop" />
          </el-form-item>
          <el-form-item prop="aot40" label="AOT40：">
            <el-input v-model="updateForm.aot40" />
          </el-form-item>
          <el-form-item prop="mda8" label="MDA8：">
            <el-input v-model="updateForm.mda8" />
          </el-form-item>
          <el-form-item prop="sum06" label="SUM06">
            <el-input v-model="updateForm.sum06" />
          </el-form-item>
          <el-form-item prop="ryl" label="RYL">
            <el-input v-model="updateForm.ryl" />
          </el-form-item>
        </el-form>
        <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
 import { fetchcropAnalysByPage,updateCasy,deletecasy,uploadcasy} from "../../../api/cropAnalys";
  import { nextTick, ref, reactive, onMounted, VueElement } from "vue";
  import { ElMessage, ElMessageBox, } from "element-plus";
  import * as XLSX from "xlsx";
  
  const dateRange = ref<[Date | null, Date | null]>([null, null]);
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    param: {
     county:'',
     city:'',
     year:''
    }
  });
  
  //获得列表
  const cropAnalysList = ref([]); // 直接使用 ref 定义数组
  let total = ref(0);
  
  function getcropAnalysList() {
    queryParams.param.earliestDetectionTime = dateRange.value[0]?.toLocaleString() || '';
    queryParams.param.latestDetectionTime = dateRange.value[1]?.toLocaleString() || '';
    console.log("query",queryParams);
    fetchcropAnalysByPage(queryParams)
      .then(res => {
  
        console.log(res.data.result.records);
        console.log("res.data.result.records", res.data.result);
        // 确保从 res 中提取数组
        cropAnalysList.value = res.data.result.records; // 如果 res 是数组
        // 或者根据实际情况调整，如：towersList.value = res.data;
        total.value = res.data.result.total;
        // console.log("tower", towersList.value);
        console.log('queryParams.value', queryParams.param)
        //queryParams.param.PointName = 
  
      })
      .catch(error => {
        console.error("Error fetching drones list:", error);
      });
  }
  //更改每页显示数量
  const handleSizeChange = val => {
    queryParams.pageSize = val;
    getcropAnalysList();
  };
  
  //更换页数
  const handleNumChange = val => {
    queryParams.pageNum = val;
    getcropAnalysList();
  };
  
  onMounted(() => {
    getcropAnalysList();
  });
  
  //上传文件
  const fieldMapping = {
    "AOT40" :"aot40", 
    "城市": "city",
    "区县" :"county",
    "作物种类": "crop",
    "MDA8" :"mda8",
    "SUM06" :"sum06",
    "RYL":"ryl",
    "年份" :"year",
  }
  const uploadedData = ref([])
  const uploadDialogVisible = ref(false)
  const convertedData = ref([])
  
  function uploadExcel() {
    uploadDialogVisible.value = true;
  }
  
  const handleFileChange = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    // 在读取数据后，处理'监测时间'列并将其转换为UTC时间
    jsonData.forEach((row) => {
      if (row['日期']) {
        // 假设 '日期' 是字符串或者日期格式
        const excelDate=row['日期']
        const date =new Date(1899, 11, 30);
        date.setDate(date.getDate() + excelDate);
        // 获取年月日、小时、分钟和秒
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，+1
        const day = String(date.getDate()).padStart(2, '0');
        
        // 将日期时间拼接成 'yyyy-mm-dd hh:mm:ss' 格式
        const formattedTime = `${year}-${month}-${day}`;

        // 将转换后的时间替换原来的时间
        row['日期'] = formattedTime;
        console.log(row['日期'])
      }
    })

    uploadedData.value = jsonData; // 将读取的数据保存到 uploadedData
  };
  
    reader.readAsArrayBuffer(file.raw);
  };
  
  const uploadData = async () => {
    let convertedData = convertFields(uploadedData)
    // 遍历 convertedData 数组，并将每个元素的 id 设置为 null
    convertedData.forEach(item => {
      item.id = 0;
    });
    console.log("convertedData",convertedData);
    uploadcasy(convertedData)
      .then(response => {
        console.log('上传成功', response);
        uploadedData.value = []; // 清空上传数据
        uploadDialogVisible.value = false; // 关闭弹窗
        ElMessage({
            message: "修改成功",
            type: "success",
            duration: 1000
          });
           getcropAnalysList()
        // 可以根据需要进一步处理响应
      })
      .catch(error => {
        console.error('上传失败', error);
        ElMessage({
          message: "修改失败",
          type: "error",
          duration: 1000
        });
        // 你可以通过 error.response 获取详细的失败信息（比如 status 或 message）
        if (error.response) {
          // 请求已发出，服务器响应了状态码，且响应体
          console.error('服务器返回错误:', error.response.data);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          console.error('没有收到响应:', error.request);
        } else {
          // 发生了一些其他错误
          console.error('请求错误:', error.message);
        }
      });
  };
  
  const convertFields = (data) => {
    console.log("datadatadatadata",data.value);
    return data.value.map(row => {
      let convertedRow = {};
      Object.keys(row).forEach(key => {
        const englishKey = fieldMapping[key];
        if (englishKey) {
          // 如果是检测时间字段（detectionTime），则转换为国际时间格式
          // if (englishKey === 'detectionTime') {
          //   convertedRow[englishKey] = formatTimestamp(row[key]); // 格式化时间戳
          // } else {
            convertedRow[englishKey] = row[key];
          // }
        }
      });
      return convertedRow;
    });
  };
  
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp); // 将时间戳转换为 Date 对象
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  
  const convertedDataWithFormattedTime = convertedData.value.map(row => {
    console.log("11111111",convertedData.value)
    return {
      ...row,
      detectionTime: formatTimestamp(row.detectionTime)
    };
  });
  
  
  
  
  //选中数据
  const selectedItems = ref([]); // 直接使用 ref 定义数组
  
  function handleSelectionChange(selected) {
        selectedItems.value = selected; // 更新选中的项
        // console.log(selectedItems.value);
  }
  //下载文件
  function exportExcel() {
    // 准备数据
    const data = selectedItems.value;
  
    // 检查数据是否为空
    if (data.length === 0) {
      console.error("没有可导出的数据");
       ElMessage({
        message: "没有可导出的数据",
        type: "error",
        duration: 1000
      });
    return;
    }
  
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  
    // 导出
    XLSX.writeFile(workbook, "data.xlsx");
  }
  
  //编辑功能
  const dialogFormVisible = ref(false);
  const formRef = ref();
  
  const updateForm = ref({
    aot40:"" ,
    city:"" ,
    county: "",
    crop: "",
    id: "",
    mda8:"" ,
    ryl: "",
    sum06:"" ,
    year: ""
  });
  
  const handleEdit = (rowData = {}) => {
    dialogFormVisible.value = true;
    console.log("rowData", rowData);
    //弹窗打开form 声称是异步的
    nextTick(() => {
      //如果是编辑
      if (rowData) {
        Object.assign(updateForm.value, rowData);
        // updateForm.value = rowData
        console.log("这里是获取编辑数据", rowData);
      }
    });
  };
  
  const confirm = async () => {
    console.log("更新内容", updateForm);
    console.log("更新内容", updateForm.value);
    updateCasy(updateForm.value)
      .then(response => {
        console.log('上传成功', response);
        dialogFormVisible.value = false; // 关闭弹窗
        ElMessage({
            message: "修改成功",
            type: "success",
            duration: 1000
          });
        // 可以根据需要进一步处理响应
        getcropAnalysList();
      })
      .catch(error => {
        console.error('修改失败', error);
        ElMessage({
          message: "修改失败",
          type: "error",
          duration: 1000
        });
        // 你可以通过 error.response 获取详细的失败信息（比如 status 或 message）
        if (error.response) {
          // 请求已发出，服务器响应了状态码，且响应体
          console.error('服务器返回错误:', error.response.data);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          console.error('没有收到响应:', error.request);
        } else {
          // 发生了一些其他错误
          console.error('请求错误:', error.message);
        }
      });
  };
  
  //删除
  const deleteItem = async (id) => {
    try {
      await ElMessageBox.confirm('是否要该条数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      console.log(id);
      await deletecasy(id);
      ElMessage({
        message: '删除成功',
        type: 'success',
        duration: 1000
      });
    } catch (error) {
      // Handle cancel or error
    }
    getcropAnalysList();
  };
  
  //重置事件
  const handleResetSearch = async () => {
    queryParams.param.year = '',
    queryParams.param.county = '',
    queryParams.param.city='',
    getcropAnalysList()
  }
  
  </script>
     <style lang="less">
  </style>